<?php
/**
 * Created by PhpStorm.
 * Author: DaXiong
 * Date: 2018/10/16
 * Time: 16:07
 */

namespace App\Http\Controllers;


use App\Jobs\PlayAnAward;
use App\Models\Activity;
use App\Models\Join;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ActivityController extends Controller
{
    /**
     * 首页活动列表 get
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function index()
    {
        $where['status'] = Activity::STATUS_1;
        $where['pay'] = Activity::PAY_1;
        $user_id = auth()->guard('api')->id();
        $info = Activity::where($where)
            ->orWhere(function ($query) {
                $query->where('status', 3)
                    ->where('pay', Activity::PAY_1)
                    ->where('updated_at', '>', Carbon::now()->subDays(1));
            })
            ->with(['join' => function ($query) use ($user_id) {
                $query->where(['user_id' => $user_id])->get();
            }])
            ->with(['user' => function ($query) {
                $query->select('id', 'nickname')->get();
            }])
            ->orderBy('status', 'ASC')
            ->orderBy('id', 'DESC')
            ->paginate(4);
        return $this->returnJson(0, '首页活动列表', $info);
    }

    /**
     * 活动详情信息 get
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function activityInfo(Request $request)
    {
        $activity_id = (int)$request->get('activity_id', '');
        $status = (int)$request->get('status', '');
        $user_id = (int)auth()->guard('api')->id();
        if ($status > 0) {
            $where['status'] = $status;
        }
        $where['id'] = $activity_id;
        $info = Activity::where($where)
            ->with([
                'user' => function ($query) {
                    $query->select('id', 'nickname','avatar')->get();
                },
                'join' => function ($query) use ($user_id, $activity_id) {
                    if ($user_id) {
                        $query->where(['user_id' => $user_id, 'activity_id' => $activity_id])->get();
                    }
                }
            ])
            ->first();
        if ($info) {
            $info = $info->makeVisible(['password'])->toArray();
            if ($info['password']) {
                $info['password'] = 1;
            }
            $info['password'] = (int)$info['password'];
            return $this->returnJson(0, '', $info);
        }
        return $this->returnJson(1);
    }

    /**
     * 活动发布提交 post
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function create(Request $request)
    {
//        $id = request('id', 0);
////        $find = Activity::withCount([ 'join' => function ($query) use($id) {
////            $query->where('activity_id', $id);
////        }])->find($id);
////        $find = Join::where('activity_id', $id)->get(['id', 'status'])->toArray();.
//        $this->playAnAward($id);
//       // $join_count= 5;
//        //$find['num1']= 5;
//        //$rand = $this->unique_rand(1, $join_count,$find['num1']);
//        dd('====');
        $data = $request->all();
        //return $this->returnJson(1,'',$data);
        $days = config('activity.defaultOpenAt');
        $open_at = Carbon::now()->parse('+' . $days . ' days')->toDateTimeString();
        $data['open_at'] = request('open_at', $open_at);
        if (!$data['open_at']) {
            $data['open_at'] = $open_at;
        }
        $data['status'] = 1;
        $data['user_id'] = auth()->guard('api')->id();

        $dateDelay = strtotime($data['open_at']) - time();
        try {
            $info = Activity::create($data);
            if ($info) {
                if($dateDelay <= 0){
                    PlayAnAward::dispatch($info)->delay(Carbon::now()->addDays($days));
                }else{
                    PlayAnAward::dispatch($info)->delay($dateDelay);
                }
                return $this->returnJson(0, '活动发布成功',$info);
            } else {
                return $this->returnJson(1, '活动发布失败');
            }
        } catch (\Exception $exception) {
            Log::error($exception);
            return $this->returnJson(1, '系统繁忙');
        }
    }

    /**
     * 图片上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function upload(Request $request)
    {
        try {
            if ($request->hasFile('giftImg') && $request->file('giftImg')->isValid()) {
                $image = $request->file('giftImg');
                $realPath = $image->getRealPath();//临时文件路径
                $name = hash_file('md5', $realPath);
                $time = date('Y-m-d');
                $fileName = $time . '/' . $name . '.' . $image->getClientOriginalExtension();
                $result = $image->storeAs('public', $fileName);
                $result = substr($result, 6);
                $return = ['path' => asset('storage' . $result)];
                return $this->returnJson(0, '', $return);
            }
            if ($request->hasFile('introduceImg') && $request->file('introduceImg')->isValid()) {
                $image = $request->file('introduceImg');
                $realPath = $image->getRealPath();//临时文件路径
                $name = hash_file('md5', $realPath);
                $time = date('Y-m-d');
                $fileName = $time . '/' . $name . '.' . $image->getClientOriginalExtension();
                $result = $image->storeAs('public', $fileName);
                $result = substr($result, 6);
                $return = ['path' => asset('storage' . $result)];
                return $this->returnJson(0, '', $return);
            }
        } catch (\Exception $e) {
            return $this->returnJson(1, $e->getMessage());
        }
    }

    /**
     * 更新/编辑 活动信息
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function update()
    {
        $data = request()->all();
        //return $this->returnJson(1,'',$data);
        $days = config('activity.defaultOpenAt');
        $open_at = Carbon::parse('+' . $days . ' days')->toDateTimeString();
        $id= (int)request('id', 0);
        $data['open_at'] = request('open_at', $open_at);
        if (!$data['open_at']) {
            $data['open_at'] = $open_at;
        }
        $data['status'] = 1;
        $data['user_id'] = auth()->guard('api')->id();

        try {
            $find = Activity::find($id);
            if(!$find){
                return $this->returnJson(1, 'ID is null');
            }
            $find->update($data);
            return $this->returnJson(0,'',$data );
        } catch (\Exception $e) {
            return $this->returnJson(1, $e->getMessage());
        }
    }

    /**
     * 手动开奖
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function lock(){
        $activity_id = (int)request('activity_id',0);
        $info = Activity::find($activity_id);
        if(!$info){
            return $this->returnJson(1, 'ID is null');
        }
        try{
            PlayAnAward::dispatch($info);
            return $this->returnJson(0);
        }catch (\Exception $e) {
            return $this->returnJson(1, $e->getMessage());
        }

    }

}
